import argparse
import subprocess


def set_system_proxy(host="127.0.0.1", port=9999):
    """设置系统代理"""
    try:
        # 获取当前网络服务
        result = subprocess.run(
            ["networksetup", "-listallnetworkservices"], capture_output=True, text=True
        )
        services = result.stdout.strip().split("\n")[1:]  # 跳过第一行的标题

        for service in services:
            if service.startswith("*"):
                continue  # 跳过禁用的服务

            # 设置 HTTP 代理
            subprocess.run(["networksetup", "-setwebproxy", service, host, str(port)])

            # 设置 HTTPS 代理
            subprocess.run(
                ["networksetup", "-setsecurewebproxy", service, host, str(port)]
            )

            print(f"已为 {service} 设置代理")

        print("系统代理设置完成")
        return True
    except Exception as e:
        print(f"设置系统代理失败: {str(e)}")
        return False


def clear_system_proxy():
    """清除系统代理"""
    try:
        # 获取当前网络服务
        result = subprocess.run(
            ["networksetup", "-listallnetworkservices"], capture_output=True, text=True
        )
        services = result.stdout.strip().split("\n")[1:]  # 跳过第一行的标题

        for service in services:
            if service.startswith("*"):
                continue  # 跳过禁用的服务

            # 关闭 HTTP 代理
            subprocess.run(["networksetup", "-setwebproxystate", service, "off"])

            # 关闭 HTTPS 代理
            subprocess.run(["networksetup", "-setsecurewebproxystate", service, "off"])

            print(f"已清除 {service} 的代理设置")

        print("系统代理已清除")
        return True
    except Exception as e:
        print(f"清除系统代理失败: {str(e)}")
        return False


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="设置系统代理")
    parser.add_argument("--host", default="127.0.0.1", help="代理主机")
    parser.add_argument("--port", default=9999, type=int, help="代理端口")
    parser.add_argument("--clear", action="store_true", help="清除代理")
    args = parser.parse_args()
    if args.clear:
        clear_system_proxy()
    else:
        set_system_proxy(args.host, args.port)
